package com.glsc.ngateway.platform.config;

import com.glsc.ngateway.platform.aspect.OperatorArgumentResolver;
import com.glsc.ngateway.platform.utils.RequestTool;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * OperatorArgumentResolver配置类，需要修改加载顺序，否则不执行
 * @author xuchang
 */
@Configuration
public class OperatorArgumentResolverAutoConfig implements InitializingBean {

    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @Resource
    private RequestTool requestTool;

    @Override
    public void afterPropertiesSet() {
        List<HandlerMethodArgumentResolver> argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();
        List<HandlerMethodArgumentResolver> customArgumentResolvers = new ArrayList<>();

        for (HandlerMethodArgumentResolver argumentResolver : argumentResolvers) {
            if(argumentResolver instanceof RequestResponseBodyMethodProcessor){
                customArgumentResolvers.add(new OperatorArgumentResolver(argumentResolver, requestTool));
            }
            customArgumentResolvers.add(argumentResolver);
        }

        requestMappingHandlerAdapter.setArgumentResolvers(customArgumentResolvers);

    }
}
